package com.lyc.platform.message.core.message.device;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import com.lyc.platform.message.core.consts.MessageConst;
import com.lyc.platform.message.core.message.Message;
import lombok.Getter;
import lombok.Setter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author liangyucheng
 * 普通的设备消息封装
 */
@Getter
@Setter
public class CommonDeviceMessage implements DeviceMessage {
    private static final long serialVersionUID = -6849794470754667710L;


    private String code;

    private String messageId;

    private String deviceId;

    private Map<String, Object> headers;

    private long timestamp = System.currentTimeMillis();


    @Override
    public Message removeHeader(String header) {
        if (headers != null) {
            this.headers.remove(header);
        }
        return this;
    }

    @Override
    public long getTimestamp() {
        return timestamp;
    }

    @Override
    public synchronized DeviceMessage addHeader(String header, Object value) {
        //初始化headers
        if (this.headers == null) {
            this.headers = new ConcurrentHashMap<>();
        }
        if (header != null && value != null) {
            this.headers.put(header, value);
        }
        return this;
    }

    @Override
    public DeviceMessage addHeaderIfAbsent(String header, Object value) {
        if (this.headers == null) {
            this.headers = new ConcurrentHashMap<>();
        }
        if (header != null && value != null) {
            this.headers.putIfAbsent(header, value);
        }
        return this;
    }

    @Override
    public JSONObject toJson() {
        JSONObject json = new JSONObject();
        BeanUtil.copyProperties(this, json, false);
        json.putOpt(MessageConst.MESSAGE_TYPE, getMessageType().name());
        return json;
    }

    @Override
    public void fromJson(JSONObject json) {
        DeviceMessage.super.fromJson(json);
    }

    @Override
    public String toString() {
        return toJson().toStringPretty();
    }
}
